package ace.oauth2.provider.base.support;

import ace.oauth2.provider.common.support.AceUser;
import org.apache.commons.collections.MapUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import java.util.AbstractMap;
import java.util.Collections;
import java.util.Map;

/**
 * @author Caspar
 * @contract 279397942@qq.com
 * @create 2020/10/23
 * @description 直接
 */
public class DefaultUserDetailsService implements AceUserDetailsService {

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        Map.Entry<String, String> entry = this.resolveTenantIdAndAccountIdByOAuth2UserName(username);
        String tenantId = entry.getKey();
        String accountId = entry.getValue();
        AceUser user = AceUser.builder()
                .username(username)
                .password(accountId)
                .enabled(true)
                .accountNonExpired(true)
                .accountNonLocked(true)
                .authorities(Collections.EMPTY_SET)
                .credentialsNonExpired(true)
                .accountId(accountId)
                .tenantId(tenantId)
                .build();
        return user;
    }

    public String buildOAuth2UserName(String tenantId, String accountId) {
        return String.format("%s:%s", tenantId, accountId);
    }

    /**
     * 从oauth2 username 中解析tenantId 与 accountId
     *
     * @param userName
     * @return key:tenantId value:accountId
     */
    public Map.Entry<String, String> resolveTenantIdAndAccountIdByOAuth2UserName(String userName) {
        String[] tenantIdAndAccountId = userName.split(":");
        String tenantId = tenantIdAndAccountId[0];
        String accountId = tenantIdAndAccountId[1];
        return Map.entry(tenantId, accountId);
    }
}
